<template>
    <div class="add-address-page">
        <header class="page-header">
            <span class="back" @click="goBack">＜</span>
            <h1 class="title">新增收货地址</h1>
        </header>
        <form class="address-form">
            <!-- 表单内容不变 -->
            <div class="form-item">
                <label class="label">联系人</label>
                <van-field v-model="form.name" type="text" placeholder="收货人姓名" required />
            </div>
            <div class="form-item">
                <label class="label">手机号</label>
                <van-field v-model="form.phone" type="tel" placeholder="收货人手机号码" required
                    :rules="[{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }]" />
            </div>
            <div class="form-item">
                <label class="label">省市区</label>
                <van-field v-model="selectedAreaText" readonly clickable placeholder="点击选择省市区" @click="showArea = true"
                    class="area-field" :class="{ 'has-selected': selectedAreaText }" />
                <van-popup v-model:show="showArea" position="bottom" :style="{ height: '70%' }" class="area-popup">
                    <van-area :area-list="areaList" @confirm="onConfirm" @cancel="showArea = false"
                        class="area-component" :columns-placeholder="['请选择省', '请选择市', '请选择区']" />
                </van-popup>
            </div>
            <div class="form-item">
                <label class="label">详细地址</label>
                <van-field v-model="form.detailAddress" type="text" placeholder="楼号、门牌" required />
            </div>
            <div class="form-item default-checkbox">
                <label class="label">设为默认</label>
                <van-switch v-model="form.isDefault" size="24px" />
            </div>
            <button type="button" class="submit-btn" @click="submit">提交</button>
        </form>
    </div>
</template>

<script setup>
import { ref } from 'vue'
import { Field, Popup, Area, Switch, showFailToast, showSuccessToast } from 'vant'  // 新增showSuccessToast
import { areaList } from '@vant/area-data'
import api from '@/api/history'
const form = ref({
    name: '',
    phone: '',
    region: {
        codes: [],
        names: []
    },
    detailAddress: '',
    isDefault: false
})

const showArea = ref(false)
const selectedAreaText = ref('')

// 地址选择确认处理（不变）
const onConfirm = (result) => {
    try {
        const selectedOptions = result.selectedOptions || result.options || result || []
        if (selectedOptions.length < 3) {
            throw new Error('请选择完整的省市区')
        }
        const [province, city, district] = selectedOptions
        let displayText = ''
        if (['710000', '810000', '820000'].includes(province.value)) {
            displayText = `${province.text}${district.text}`
        } else if (['110000', '310000', '120000', '500000'].includes(province.value)) {
            displayText = `${province.text}${district.text}`
        } else {
            displayText = `${province.text}${city.text}${district.text}`
        }
        selectedAreaText.value = displayText
        form.value.region = {
            codes: selectedOptions.map(opt => opt.value),
            names: [province.text, city.text, district.text]
        }
        showArea.value = false
    } catch (error) {
        console.error('地区选择处理失败:', error)
        showFailToast(error.message || '地区选择失败，请重试')
    }
}

// 页面返回（不变）
const goBack = () => history.back()

// 表单提交验证（修改：添加返回值）
const handleSubmit = () => {
    if (!selectedAreaText.value) {
        showFailToast('请选择省市区')
        return false
    }
    if (!form.value.name.trim()) {
        showFailToast('请输入联系人姓名')
        return false
    }
    if (!form.value.phone.trim()) {
        showFailToast('请输入手机号码')
        return false
    }
    if (!/^1[3-9]\d{9}$/.test(form.value.phone)) {
        showFailToast('请输入正确的手机号码')
        return false
    }
    if (!form.value.detailAddress.trim()) {
        showFailToast('请输入详细地址')
        return false
    }


    // 所有验证通过返回true
    return true
}

// 初始化已有地址数据（编辑场景，不变）
const initAddressData = (address) => {
    if (address) {
        form.value = {
            name: address.name,
            phone: address.phone,
            region: {
                codes: address.regionCodes,
                names: address.regionNames
            },
            detailAddress: address.detailAddress,
            isDefault: address.isDefault
        }
        selectedAreaText.value = address.regionNames.join('')
    }
}
function submit() {
    const fullAddress = `${selectedAreaText.value}${form.value.detailAddress}`;
    api.post('/address', {
        name: form.value.name,
        phone: form.value.phone,
        address: fullAddress,
        is_default: form.value.isDefault
    }).then((res) => {
        console.log('提交成功:', res);
        alert('地址添加成功');
        goBack();
    }).catch((err) => {
        console.error('提交失败:', err);
        alert('地址添加失败，请重试');
    });
}
</script>

<style scoped>
/* 样式不变 */
.add-address-page {
    padding: 15px;
    max-width: 600px;
    margin: 0 auto;
}

.page-header {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
}

.back {
    font-size: 20px;
    cursor: pointer;
    margin-right: 10px;
}

.title {
    font-size: 18px;
    font-weight: bold;
}

.form-item {
    margin-bottom: 15px;
}

.label {
    display: block;
    font-size: 14px;
    color: #333;
    margin-bottom: 5px;
}

.submit-btn {
    background-color: #f40;
    color: white;
    padding: 10px;
    border: none;
    border-radius: 4px;
    font-size: 16px;
    cursor: pointer;
    margin-top: 10px;
    width: 100%;
}

.area-field.has-selected .van-field__value {
    color: #333 !important;
    font-weight: 500;
}

.van-field__value {
    text-align: left !important;
}

.area-popup {
    z-index: 2001;
}

.van-overlay {
    z-index: 2000;
}

.area-component {
    height: 100%;
}

.default-checkbox {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10px 0;
}
</style>